<template>
  <div class="role-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 使用封装的表格组件 -->
      <basic-table
        :loading="loading"
        :table-data="tableData"
        :columns="columns"
        :show-selection="true"
        :total="total"
        @selection-change="handleSelectionChange"
      >
        <!-- 状态列插槽 -->
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <el-button type="primary" link @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button type="danger" link @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </basic-table>
    </el-card>

    <!-- 添加角色弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="roleForm.roleSort" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import BasicTable from '@/components/BasicTable/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 查询参数
const queryParams = reactive({
  roleName: '',
  pageNum: 1,
  pageSize: 10,
});

// 表格加载状态
const loading = ref(false);

// 原始数据，用于搜索时过滤
const originalData = ref([
  {
    id: 1,
    roleName: '超级管理员',
    roleKey: 'admin',
    roleSort: 1,
    status: 1,
    createTime: '2024-03-20 10:00:00',
  },
  {
    id: 2,
    roleName: '普通用户',
    roleKey: 'user',
    roleSort: 2,
    status: 1,
    createTime: '2024-03-20 11:00:00',
  },
]);

// 表格数据改为计算属性
const tableData = computed(() => {
  const { roleName } = queryParams;
  if (!roleName) return originalData.value;

  return originalData.value.filter((item) =>
    item.roleName.toLowerCase().includes(roleName.toLowerCase()),
  );
});

// 总条数也改为计算属性
const total = computed(() => tableData.value.length);

// 表格列配置
const columns = [
  { prop: 'roleName', label: '角色名称', minWidth: 120 },
  { prop: 'roleKey', label: '权限字符', minWidth: 120 },
  { prop: 'roleSort', label: '显示顺序', width: 100 },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    slot: 'status',
  },
  {
    prop: 'createTime',
    label: '创建时间',
    minWidth: 160,
    sortable: true,
  },
  {
    prop: 'action',
    label: '操作',
    width: 150,
    slot: 'action',
  },
];

// 选中项变化
const handleSelectionChange = (selection) => {
  console.log('选中的行：', selection);
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  // 搜索已通过计算属性自动完成
};

// 重置
const handleReset = () => {
  queryParams.roleName = '';
  queryParams.pageNum = 1;
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const roleFormRef = ref(null);

// 表单数据
const roleForm = reactive({
  id: undefined,
  roleName: '',
  roleKey: '',
  roleSort: 1,
  status: 1,
});

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  roleKey: [{ required: true, message: '请输入权限字符', trigger: 'blur' }],
  roleSort: [{ required: true, message: '请输入显示顺序', trigger: 'blur' }],
};

// 重置表单
const resetForm = () => {
  roleForm.id = undefined;
  roleForm.roleName = '';
  roleForm.roleKey = '';
  roleForm.roleSort = 1;
  roleForm.status = 1;
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
};

// 新增按钮点击
const handleAdd = () => {
  dialogTitle.value = '新增角色';
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色';
  resetForm();
  // 复制数据到表单
  Object.assign(roleForm, row);
  dialogVisible.value = true;
};

// 表单提交
const handleSubmit = async () => {
  if (!roleFormRef.value) return;

  await roleFormRef.value.validate((valid) => {
    if (valid) {
      const isEdit = roleForm.id !== undefined;

      if (isEdit) {
        // 编辑现有数据
        const index = originalData.value.findIndex(
          (item) => item.id === roleForm.id,
        );
        if (index !== -1) {
          originalData.value[index] = {
            ...originalData.value[index],
            ...roleForm,
            createTime: originalData.value[index].createTime, // 保留原创建时间
          };
        }
      } else {
        // 新增数据
        const newRole = {
          ...roleForm,
          id: originalData.value.length + 1,
          createTime: new Date().toLocaleString(),
        };
        originalData.value.push(newRole);
      }

      ElMessage.success(`${isEdit ? '修改' : '新增'}成功`);
      dialogVisible.value = false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除角色"${row.roleName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const index = originalData.value.findIndex((item) => item.id === row.id);
      if (index !== -1) {
        originalData.value.splice(index, 1);
        ElMessage.success('删除成功');
      }
    })
    .catch(() => {});
};
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
